package com.zhan.signalling.connect.listener;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.BroadcastOperations;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.zhan.signalling.commons.Constants;
import com.zhan.signalling.commons.SocketEvent;
import com.zhan.signalling.message.Result;

public class ZhanDisconnectListener implements DisconnectListener {
	
	private final static Logger log = LoggerFactory.getLogger(ZhanDisconnectListener.class);
	
	public void onDisconnect(SocketIOClient client) {
		String content = "disconnect";
		Integer status = Constants.SUCCESS;
		JSONObject user = client.get(Constants.USER_KEY);
		String groupId = client.get(Constants.GROUP_KEY);
		client.leaveRoom(Constants.GROUP_KEY);
		log.info(user + "leave " + client.getNamespace().getName() + ":" + groupId);
		if(client.getNamespace() != null && StringUtils.isNotBlank(groupId)) {
			if(client.getNamespace().getRoomOperations(groupId) != null) {
				BroadcastOperations operation = client.getNamespace().getRoomOperations(groupId);
				operation.sendEvent(SocketEvent.EXIT_GROUP_EVENT, new Result(user, Constants.SUCCESS));
			}
		}
		client.del(Constants.USER_KEY);
		client.del(Constants.USER_TOKEN);
		client.del(Constants.GROUP_KEY);
		client.del(Constants.USER_TYPE);
		log.info(JSONObject.toJSONString(new Result(content,status)));
	}

}
